package com.fz.config;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.fz.common.GlobalAll;
import com.fz.security.utils.SecurityUtils;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;


/**
 *  执行持久化操作时 处理默认数据填充
 */
@Component
public class MetaHandler implements MetaObjectHandler {

    /**
     * 新增数据执行
     * @param metaObject
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        this.setFieldValByName(GlobalAll.CREATE_TIME, LocalDateTime.now(), metaObject);
        if(ObjectUtil.isNotNull(SecurityUtils.getCurrentUser())){
            this.setFieldValByName(GlobalAll.CREATE_BY, SecurityUtils.getCurrentUser().getId(), metaObject);
        }
        this.setFieldValByName(GlobalAll.DELETE_STATUS,GlobalAll.DELETE_STATUS_NO,metaObject);
        this.setFieldValByName(GlobalAll.UPDATE_TIME, LocalDateTime.now(), metaObject);
        //默认乐观锁配置从1开始
        this.setFieldValByName(GlobalAll.VERSION_LOCK, 1, metaObject);
    }

    /**
     * 更新数据执行
     * @param metaObject
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        if(ObjectUtil.isNotNull(SecurityUtils.getCurrentUser())){
            this.setFieldValByName(GlobalAll.UPDATE_BY, SecurityUtils.getCurrentUser().getId(), metaObject);
        }
        this.setFieldValByName(GlobalAll.UPDATE_TIME, LocalDateTime.now(), metaObject);
    }
}
